#include <libmpd/libmpd.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include "config.h"
#include "dwmstatus_types.h"
#include "draw_statusbar.h"

String mpd_formated;

pthread_mutex_t mpdstatus_exclusive = PTHREAD_MUTEX_INITIALIZER;
MpdObj *mpd_handle = NULL;

void set_mpdstatus(char *my_status) {

  pthread_mutex_lock(&mpdstatus_exclusive);
  COPY(mpd_formated, my_status, sizeof(mpd_formated));
  pthread_mutex_unlock(&mpdstatus_exclusive);
}

void get_mpdstatus(char *dest, size_t size) {
  pthread_mutex_lock(&mpdstatus_exclusive);
  COPY(dest, mpd_formated, size);
  pthread_mutex_unlock(&mpdstatus_exclusive);
}

void mpdstatus_changed(MpdObj *mi, ChangedStatusType what, void *userdate) {

  String current_song;
  String current_state;
  String formatted_status;

  if (what & MPD_CST_SONGID || what & MPD_CST_STATE) {
  memset(current_song, 0, sizeof(current_song));
  memset(current_state, 0, sizeof(current_state));

  mpd_Song *song = mpd_playlist_get_current_song(mi);
  if (song)
    COPY(current_song, song->title, sizeof(current_song));

  switch(mpd_player_get_state(mi)) {
    case MPD_PLAYER_PLAY:
      COPY(current_state, PLAYING, sizeof(current_state));
      break;
    case MPD_PLAYER_PAUSE:
      COPY(current_state, PAUSED, sizeof(current_state));
      break;
    case MPD_PLAYER_STOP:
      COPY(current_state, STOPPED, sizeof(current_state));
      break;
  }
  
  snprintf(formatted_status, sizeof(formatted_status), MPD_FORMAT, current_song, current_state);
  set_mpdstatus(formatted_status);
  redraw_status();
  }
}


void mpdstatus_init() {

  mpd_handle = mpd_new(MPD_HOST, MPD_PORT, MPD_PASSWORD);

  mpd_signal_connect_status_changed(mpd_handle, mpdstatus_changed, NULL);

  mpd_set_connection_timeout(mpd_handle, MPD_CONNECTION_TIMEOUT);

  if (! mpd_connect( mpd_handle)) {
    mpd_send_password( mpd_handle);
    mpd_status_update( mpd_handle);
    mpdstatus_start();
  }
}

void mpdstatus_start() {
  pthread_t mpdstatus_thread;

  pthread_create(&mpdstatus_thread, NULL, mpdstatus_loop, NULL);
}

void *mpdstatus_loop(void *ptr) {
  for (;;usleep(MPD_UPDATE))
    mpd_status_update(mpd_handle);
}


